package com.gxa.realm;

import com.gxa.mapper.admin.AdminMapper;
import com.gxa.mapper.admin.UserMapper;
import com.gxa.pojo.Menu;
import com.gxa.pojo.Role;
import com.gxa.pojo.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdminMapper adminMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String number = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        User user = userMapper.selectUserByNumber(number);
        List<Menu> menuList =adminMapper.selectMenuByUserId(user.getId()+"");
        Set<String> menuSet =new HashSet<>();
        for (Menu m:menuList){
            menuSet.add(m.getTitle());
        }
        simpleAuthorizationInfo.setStringPermissions(menuSet);
        return simpleAuthorizationInfo;

    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String number = (String) authenticationToken.getPrincipal();
        User user = userMapper.selectUserByNumber(number);
        System.out.println("==============");
        if (user!=null){
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(number, user.getPassword(), ByteSource.Util.bytes("?zk"), this.getName());
            System.out.println(info);
            return info;
        }
        return null;
    }
}
